package com.hx.quartz;

import com.hx.pojo.Mood;
import com.hx.pojo.UserMoodPraiseRel;
import com.hx.service.MoodService;
import com.hx.service.UserMoodPraiseRelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 开启定时任务
 * 定时从redis中拉取点赞记录，并更新在mysql中。
 * 配置类  注解的形式  独立的线程
 */
@Configuration  //开启配置类
@EnableScheduling //开启定时器任务
@Slf4j
public class PraiseSaveFromRedisToMysqlJob {

    @Resource
    private RedisTemplate redisTemplate;

    //用于存放不同说说id的redis(HashSet)的主键key,value对应不同的说说id
    private static final String PRAISE_HASH_KEY = "praise.mood.id.list.key";

    @Resource
    private MoodService moodService;

    @Resource
    private UserMoodPraiseRelService userMoodPraiseRelService;

    //每10秒执行一次定时任务
    @Scheduled(cron = "*/10 * * * * *")
    public void savePraiseNumFromRedisToMysql(){

        //step1 查看redis中所有缓存的moodId
        Set<String> moodIds = redisTemplate.opsForSet().members(PRAISE_HASH_KEY);
        if (CollectionUtils.isEmpty(moodIds)){
            log.info("redis中并未缓存 moodId 有关信息...");
            return;
        }

        //step2 查看redis中，每个moodId对应的UserId
        for (String moodId : moodIds) {

            Set<String> userIds = redisTemplate.opsForSet().members(moodId);

            if (CollectionUtils.isEmpty(userIds)){
                log.info("redis中并未缓存说说id为{}的记录...",moodId);
                continue;
            }

            //step3 将redis中每条userId相关的记录，保存在mysql的关联表中
            for (String userId : userIds) {
                UserMoodPraiseRel userMoodPraiseRel = new UserMoodPraiseRel();
                userMoodPraiseRel.setMoodId(moodId);
                userMoodPraiseRel.setUserId(userId);
                userMoodPraiseRelService.save(userMoodPraiseRel);
            }
            log.info("redis向mysql中更新关联信息记录，成功...");

            //step4 更新mysql数据表中的点赞记录
            Mood mood = moodService.findMoodById(moodId);
            mood.setPraiseNum(mood.getPraiseNum() +
                    redisTemplate.opsForSet().size(moodId).intValue());
            moodService.updateMood(mood);
            log.info("redis向mysql中更新点赞记录，成功...");

            //step5 清除redis的moodId数据
            redisTemplate.delete(moodId);
            log.info("成功清除redis中的说说id{}记录...",moodId);
        }

        //step6 清楚redis的PRAISE KEY
        redisTemplate.delete(PRAISE_HASH_KEY);
        log.info("成功清除redis中的点赞KEY:{}",PRAISE_HASH_KEY);
    }
}
